import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:baseProjectFlutter/widgets_common/image/svg_widget.dart';

import '../../config/theme.dart';
import '../../utils/common/assets_utils.dart';

extension ImageExtens on String {
  Widget showImage({double? width, double? height, BoxFit fit = BoxFit.contain, String? defImage}) {
    return endsWith("svg") ? SvgWidget(this, width: width, height: height, fit: fit) : ImageX(url: this, width: width, height: height, fit: fit, defImage: defImage);
  }
}

//封装图片加载控件，增加图片加载失败时加载默认图片
class ImageX extends StatelessWidget {
  Image? image;
  final String url;
  final double? width;
  final double? height;
  final BoxFit fit;

  final String _defImage;
  final themeVm = Get.put(ThemeVm());

  ImageX({this.url = '', this.image, this.width, this.height, this.fit = BoxFit.contain, String? defImage}) : _defImage = defImage ?? "assets/images/ic_launcher.png";

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      var isLocal = false;
      var urlResult = url;
      if (url.startsWith("assets")) {
        isLocal = true;
        final isDarkMode = themeVm.themeMode == ThemeMode.dark;
        urlResult = isDarkMode ? AssetsUtils.getDarkAssetPath(url) : url;
      } else if (url.startsWith("http://") || url.startsWith("https://")) {
        isLocal = false;
      }
      return isLocal
          ? Image.asset(
              urlResult,
              width: width,
              height: height,
              fit: fit,
            )
          : Image.network(
              urlResult,
              width: width,
              height: height,
              fit: fit,
              errorBuilder: (context, error, stackTrace) {
                return Image.asset(
                  _defImage,
                  width: width,
                  height: height,
                );
              },
            );
    });
  }
}
